#include <iostream>
#include <memory>

using std::cout;
using std::endl;
using std::unique_ptr;
using std::shared_ptr;

class Point
: public std::enable_shared_from_this<Point>
{
public:
    Point(int ix = 0, int iy = 0)
    : _ix(ix)
    , _iy(iy)
    {
        cout << "Point(int = 0, int = 0)"  << endl;
    }

    void print() const
    {
        cout << "(" << _ix
             << ", " << _iy
             << ")" << endl;
    }

    //Point * const this
    /* Point *addPoint(Point *pt) */
    shared_ptr<Point> addPoint(Point *pt)
    {
        _ix += pt->_ix;
        _iy += pt->_iy;

        /* return this; */
        /* return shared_ptr<Point>(this); */
        return shared_from_this();
    }

    ~Point()
    {
        cout << "~Point()" << endl;
    }
private:
    int _ix;
    int _iy;
};

void test()
{
    //使用了不同的智能指针托管同一块堆空间
    Point *pt = new Point(1, 2);
    unique_ptr<Point> up(pt);
    unique_ptr<Point> up2(pt);
}

void test2()
{
    //使用了不同的智能指针托管同一块堆空间
    unique_ptr<Point> up(new Point(1, 2));
    unique_ptr<Point> up2(new Point(3, 4));
    up.reset(up2.get());
}

void test3()
{
    //使用了不同的智能指针托管同一块堆空间
    Point *pt = new Point(1, 2);
    shared_ptr<Point> sp(pt);
    /* shared_ptr<Point> sp2(pt); */
    shared_ptr<Point> sp2(sp);
}

void test4()
{
    //使用了不同的智能指针托管同一块堆空间
    shared_ptr<Point> sp(new Point(1, 2));
    shared_ptr<Point> sp2(new Point(3, 4));
    sp.reset(sp2.get());
}

void test5()
{
    shared_ptr<Point> sp(new Point(1, 2));
    cout << "sp = ";
    sp->print();

    cout << endl;
    shared_ptr<Point> sp2(new Point(3, 4));
    cout << "sp2 = ";
    sp2->print();

    cout << endl;
    shared_ptr<Point> sp3(sp->addPoint(sp2.get()));
    cout << "sp3 = ";
    sp3->print();
}

int main(int argc, char **argv)
{
    test5();
    return 0;
}

